import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {AdminService} from '../admin.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Location} from '@angular/common';

@Component({
    selector: 'app-changepwd',
    templateUrl: './changepwd.component.html',
})
export class ChangepwdComponent implements OnInit {
    validateForm: FormGroup;

    constructor(private fb: FormBuilder,
                private msg: NzMessageService,
                private location: Location,
                private adminService: AdminService) {
        this.validateForm = this.fb.group({
            newPwd: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9]*$/), Validators.maxLength(16), Validators.minLength(6)]],
            newPwdConfirm: ['', [this.confirmValidator]],
        });
    }

    ngOnInit() {
    }

    /**
     * 验证确认密码
     * @param {FormControl} control
     * @returns {{[p: string]: boolean}}
     */
    confirmValidator = (control: FormControl): { [s: string]: boolean } => {
        if (!control.value) {
            // 确认密码为空
            return {required: true};
        } else if (control.value !== this.validateForm.controls.newPwd.value) { // 密码不一致
            return {confirm: true, error: true};
        }
    };

    /**
     * 提交修改
     */
    submit() {
        const res = this.validateForm.value;
        this.adminService.changeMinePwd(res['newPwd']).subscribe(res => {
            this.msg.success('修改成功');
            this.location.back();
        }, e => {
            // this.msg.error('修改失败');
        });
    }

    /**
     * 返回
     */
    back() {
        this.location.back();
    }
}
